package linc.cool.单例模式;

import lombok.extern.slf4j.Slf4j;

import java.util.Objects;

/**
 * @author yqlin
 * @date 2021/12/29 12:19 AM
 * @description 懒汉式单例
 */
@Slf4j
public class LazySingleton {
    /**
     * 保证 instance 在所有线程中同步
     */
    private static volatile LazySingleton instance = null;

    /**
     * private 避免类在外部被实例化
     */
    private LazySingleton() {

    }

    /**
     * getInstance 方法前加同步
     */
    public static synchronized LazySingleton getInstance() {
        if (Objects.isNull(instance)) {
            instance = new LazySingleton();
        }
        return instance;
    }

    public static void main(String[] args) {
        new Thread(() -> {
            log.debug("thread: {}", getInstance().hashCode());
        }).start();
        new Thread(() -> {
            log.debug("thread: {}", getInstance().hashCode());
        }).start();
        new Thread(() -> {
            log.debug("thread: {}", getInstance().hashCode());
        }).start();
    }
}
